package fms.service;

import fms.thread.FtpUpDownLoadThread;
import fms.util.ConfUtil;
import fms.util.FtpUpDownLoadParamVo;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created with IntelliJ IDEA.
 * Desc: 本服务用于本地服务器与其他FTP服务器之间进行文件上传/下载功能；
 *       每隔10分钟分别开启一个FTP上传和下载文件的线程
 */
public class FtpUpDownLoadService {
    private static Logger ftpUpDownLoadLogger = Logger.getLogger("ftpUpDownLoad");

    /**
     * FTP上传下载工具，入口函数
     */
    public static void main(String[] args) {
        try {
            String logFilePath= ConfUtil.props.getProperty("log4jconfig");
            PropertyConfigurator.configure(logFilePath);
            ftpUpDownLoadLogger.info("FTP文件上传与下载服务已启动！");

            // 记录要执行的FTP上传任务集合
            ArrayList uploadTaskList = new ArrayList();
            // 记录要执行的FTP上传任务集合
            ArrayList downloadTaskList = new ArrayList();

            File fBaseParam = new File(ConfUtil.props.getProperty("baseParamFilePath"));
            SAXReader readerBaseParam = new SAXReader();
            Document paraseRuleDoc = readerBaseParam.read(fBaseParam);
            // 获取FTP上传任务列表
            List uploadTaskParams = paraseRuleDoc.selectNodes("/baseParamter/FtpUpDownLoadService/UploadPipelinesParam/UploadPipeline");
            Iterator it = uploadTaskParams.iterator();
            while (it.hasNext()) {
                Element uploadTaskParam = (Element) it.next();
                FtpUpDownLoadParamVo ftpUpDownLoadParamVo = new FtpUpDownLoadParamVo();
                ftpUpDownLoadParamVo.setLocaldir(uploadTaskParam.attributeValue("localdir"));
                ftpUpDownLoadParamVo.setIp(uploadTaskParam.attributeValue("ip"));
                ftpUpDownLoadParamVo.setPort(Integer.valueOf(uploadTaskParam.attributeValue("port")));
                ftpUpDownLoadParamVo.setUserName(uploadTaskParam.attributeValue("username"));
                ftpUpDownLoadParamVo.setPassWord(uploadTaskParam.attributeValue("passwd"));
                ftpUpDownLoadParamVo.setFtpdir(uploadTaskParam.attributeValue("ftpdir"));
                ftpUpDownLoadParamVo.setBackupdir(uploadTaskParam.attributeValue("backupdir"));
                uploadTaskList.add(ftpUpDownLoadParamVo);
            }

            // 获取FTP下载任务列表
            List downloadTaskParams = paraseRuleDoc.selectNodes("/baseParamter/FtpUpDownLoadService/DownloadPipelinesParam/DownloadPipeline");
            it = downloadTaskParams.iterator();
            while (it.hasNext()) {
                Element downloadTaskParam = (Element) it.next();
                FtpUpDownLoadParamVo ftpUpDownLoadParamVo = new FtpUpDownLoadParamVo();
                ftpUpDownLoadParamVo.setLocaldir(downloadTaskParam.attributeValue("localdir"));
                ftpUpDownLoadParamVo.setIp(downloadTaskParam.attributeValue("ip"));
                ftpUpDownLoadParamVo.setPort( Integer.valueOf(downloadTaskParam.attributeValue("port")) );
                ftpUpDownLoadParamVo.setUserName(downloadTaskParam.attributeValue("username"));
                ftpUpDownLoadParamVo.setPassWord(downloadTaskParam.attributeValue("passwd"));
                ftpUpDownLoadParamVo.setFtpdir(downloadTaskParam.attributeValue("ftpdir"));
                ftpUpDownLoadParamVo.setBackupdir(downloadTaskParam.attributeValue("backupdir"));
                downloadTaskList.add(ftpUpDownLoadParamVo);
            }

            // 构造一个ScheduledThreadPoolExecutor对象，并且设置它的容量为2个
            ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(2);

            if (uploadTaskList.size() > 0) {
                ftpUpDownLoadLogger.debug("构造FTP上传功能主线程！");
                // FTP上传功能主线程
                FtpUpDownLoadThread uploadThread = new FtpUpDownLoadThread(uploadTaskList, "up");
                ftpUpDownLoadLogger.debug("启动FTP上传功能主线程！");
                // 隔0分钟后开始执行任务，并且在上一次任务执行完成后隔10分钟再执行一次（尽量释放内存）；
                stpe.scheduleWithFixedDelay(uploadThread, 0, 10, TimeUnit.MINUTES);
            }

            if (downloadTaskList.size() > 0) {
                ftpUpDownLoadLogger.debug("构造FTP下载功能主线程！");
                // FTP下载功能主线程
                FtpUpDownLoadThread downloadThread = new FtpUpDownLoadThread(downloadTaskList, "down");
                ftpUpDownLoadLogger.debug("启动FTP下载功能主线程！");
                // 隔0分钟后开始执行任务，并且在上一次任务执行完成后隔10分钟再执行一次（尽量释放内存）；
                stpe.scheduleWithFixedDelay(downloadThread, 0, 10, TimeUnit.MINUTES);
            }
        } catch (final Exception e) {
            ftpUpDownLoadLogger.error("程序异常终止：" + e.getMessage());
        }
    }

}
